'''
Created on Mar 2, 2013

@author: Gabriel
'''
import db.databaseMgr
import os
import re

#
#  The base directory where to start searching for media files
#
SMB_HOST = '//MYBOOKLIVE/'
BASE_MEDIA_DIR = 'Public/Shared Videos/'
#BASE_MEDIA_DIR = 'Public/Development/'
MOVIES_DIR = 'Movies'
TV_SHOWS_DIR = 'TV'

#
#  SMB extension to be prefixed to the file path so boxee can access it as a URL (ex.: smb://host/dir/file
#
SMB_URL_PREFIX = 'smb:'

VIDEO_EXTENSIONS_PATTERN = ".*\.mkv|.*\.avi|.*\.mpg|.*\.mp4|.*\.ts"

def __isVideoFile(path):
    return re.match(VIDEO_EXTENSIONS_PATTERN, path, re.IGNORECASE)

def __isDirectory(path):
    return os.path.isdir(path)

def listDirRecodingPathNames(directory):
#    print sys.getfilesystemencoding()
    entries = os.listdir(directory)
    if entries :
        recodedPath = []
        for path in entries :
            print path
            print len(path)
#            recodedPath.append(path.decode('cp1252').encode('unicode-escape'))
            print path.decode('cp1252').encode('cp1252')
            print len(path.decode('cp1252'))
            print recodedPath[-1]
            print len(recodedPath[-1])
        print recodedPath
    return recodedPath


def listVideos(directory):
    videos = []
    entries = os.listdir(unicode(directory))
    if entries :
        sortedEntries = sorted(entries)
        for entry in sortedEntries :
            entryPath = directory + '/' + entry
            if __isDirectory(entryPath) : 
                videos.extend(listVideos(entryPath))
            else :
                if __isVideoFile(entryPath):
                    videos.append(SMB_URL_PREFIX + entryPath)
    return videos


def discoverVideos(directory):
    tvShows = []
    entries = os.listdir(directory)
    # First level directories are the series, subsequent are seasons
    for entry in entries :
        entryPath = directory + '/' + entry
        if __isDirectory(entryPath) :
            print entry 
            show = {'name':entry, 'episodes':listVideos(entryPath)}
            tvShows.append(show)
    return tvShows


if __name__ == '__main__':
    
    # enumerate shows
    # List the files for each show
    # 
#    print db.databaseMgr.getVideo('BBC Nature')['episodes'][1]
    database = {}
    
    database['shows'] = discoverVideos(SMB_HOST + BASE_MEDIA_DIR + TV_SHOWS_DIR)
    database['movies'] = discoverVideos(SMB_HOST + BASE_MEDIA_DIR + MOVIES_DIR)
    
    db.databaseMgr.createDatabase(database)    
